import AdmZip from 'adm-zip'
import iconv from 'iconv-lite'
import cheerio from 'cheerio';

import { CHANNEL } from './channels'
import { httpsGet } from './http'

const ipcMain = require('electron').ipcMain

ipcMain.on(CHANNEL, async (event, ...args) => {
  let response
  let error
  try {
    const data = await loadPage()
    data.codes = await loadCode(data.href)
    response = data
  } catch (e) {
    error = e
  } finally {
    event.sender.send(CHANNEL, response, error)
  }
})

async function loadPage(): Promise<any> {
  const base = 'https://idea.medeming.com/idea/'
  const buf = await httpsGet(base)

  const data: any = {}
  const $ = cheerio.load(buf, {})

  $('div').each((i, el) => {
    const $el = $(el)
    if (el.childNodes.length === 1 && el.childNodes[0].type === 'text') {
      const text = $el.text()
      if ($el.text().indexOf('更新日期') >= 0) {
        data.updateDate = text
        return false
      }
    }
  })

  $('a').each((i, el) => {
    const $el = $(el)
    if ($el.text().indexOf('点击下载') >= 0) {
      const href = $el.attr('href')
      const url = new URL(href, base)
      data.href = url.href
      return false
    }
  })

  return data
}

async function loadCode(url: string): Promise<any> {
  const buf = await httpsGet(url)
  const zip = new AdmZip(buf)
  const entries = zip.getEntries()
  return entries.filter(({entryName, isDirectory}) => {
    return !isDirectory && entryName.endsWith('.txt')
  }).map(entry => {
    const {rawEntryName} = entry
    const encoding = 'gb2312'/*Chardet.detect(rawEntryName) || 'utf8'*/
    const name = iconv.decode(rawEntryName, encoding)

    const content = iconv.decode(zip.readFile(entry), encoding)

    return {name: name.substring(0, name.length - 4), content}
  })
}
